// pages/notification.js
const tool = require("../../utils/tool")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '',
    type: '',

    management_total: 0,
    management_list: undefined,
    management_page: 1,
    management_size: 10,

    add_userList: [],
    add_input: '',
    add_cansee: 0,
    add_selectedUserList: [],

    detail_data: undefined,
    detail_nodes:'',

    userList_page: 1,
    userList_size: 10,
    userList_list: undefined,
    userList_unread: 0,
    userList_total: 0,
    userList_subScribe: false,
  },

  back() {
    wx.navigateBack()
  },

  async handleAddNotificationClick() {
    tool.navigateTo(this, 'notification', {
      type: 'add'
    })
  },

  async init_management() {
    tool.loading.show()
    this.setData({
      management_page: 1
    })
    let re = await tool.requestMethod('/notification/managementList', {
      page: this.data.management_page,
      size: this.data.management_size
    })
    console.log(re)
    tool.loading.hide()
    if (re.status == 1) {
      this.setData({
        management_total: re.results.total,
        management_list: re.results.data
      })
    } else {
      wx.showModal({
        title: '提示',
        content: re.content,
        showCancel: false,
        complete: (res) => {
          wx.navigateBack()
        }
      })
    }
  },

  management_handleShowNtificationDetailPage(e) {
    tool.navigateTo(this, 'notification', {
      type: 'detail',
      time: e.currentTarget.dataset.time
    })
  },

  async init_add() {
    tool.loading.show()
    let re = await tool.requestMethod('/userList')
    tool.loading.hide()
    if (re.status == 1) {
      this.setData({
        add_userList: re.results
      })
    } else {
      wx.showModal({
        title: '提示',
        content: re.content,
        showCancel: false,
        complete: (res) => {
          wx.navigateBack()
        }
      })
    }
  },

  add_handleChangeCansee(e) {
    this.setData({
      add_cansee: e.currentTarget.dataset.index
    })
  },

  add_handleInput(e) {
    this.setData({
      add_input: e.detail.value
    })
  },

  add_handleSelectUser(e) {
    e = parseInt(e.detail.value)
    let t = this.data.add_selectedUserList
    t = [this.data.add_userList[e], ...t]
    this.setData({
      add_selectedUserList: t
    })
  },

  add_handleDeleteUserByIndex(e) {
    wx.showModal({
      title: '提示',
      content: '是否删除此用户？',
      complete: async (res) => {
        if (res.cancel) {

        }

        if (res.confirm) {
          let t = this.data.add_selectedUserList
          this.setData({
            add_selectedUserList: [...t.slice(0, e.currentTarget.dataset.index), ...t.slice(e.currentTarget.dataset.index + 1)]
          })
        }
      }
    })

  },

  async add_handleSubmit(e) {
    const getUserAccountList = () => {
      let re = []
      for (let i = 0; i < this.data.add_selectedUserList.length; i++) {
        re.push(this.data.add_selectedUserList[i].account)
      }
      return JSON.stringify(re)
    }
    if (this.data.add_input == '') {
      tool.showToast('请输入通知内容')
      return
    }
    if (this.data.add_cansee == 1 && this.data.add_selectedUserList.length == 0) {
      tool.showToast('请选择谁可见此通知')
      return
    }
    if (this.data.add_cansee == 2 && this.data.add_selectedUserList.length == 0) {
      tool.showToast('请选择谁不可见此通知')
      return
    }
    tool.loading.show()
    let re = await tool.requestMethod('/notification/add', {
      account: this.data.loginedUserInfo.account,
      content: this.data.add_input,
      cansee: this.data.add_cansee == 1 ? getUserAccountList() : '',
      cantsee: this.data.add_cansee == 2 ? e.currentTarget.datasetgetUserAccountList() : '',
      forcemessage: e.currentTarget.dataset.forcemessage
    })
    tool.loading.hide()
    if (re.status == 1) {
      wx.showModal({
        title: '提示',
        content: '发布成功',
        showCancel: false,
        complete: (res) => {
          wx.navigateBack()
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: re.content,
        showCancel: false,
        complete: (res) => {

        }
      })
    }
  },

  async init_detail(e) {
    tool.loading.show()
    let re = await tool.requestMethod('/notification/detail', {
      account: this.data.loginedUserInfo.account,
      userInfo: (this.data.loginedUserInfo.type == 'admin'),
      time: e.time
    })
    tool.loading.hide()
    if (re.status == 1) {
      this.setData({
        detail_data: re.results,
        detail_nodes:tool.getHTMLString(re.results.content)
      })
    } else {
      wx.showModal({
        title: '提示',
        content: re.content,
        showCancel: false,
        complete: (res) => {
          wx.navigateBack()
        }
      })
    }
  },

  async detail_read() {
    if (this.data.detail_data.isRead == true) return
    tool.loading.show()
    let re = await tool.requestMethod('/notification/read', {
      account: this.data.loginedUserInfo.account,
      time: this.data.detail_data.time
    })
    tool.loading.hide()
    if (re.status == 1) {
      let t = this.data.detail_data
      t.isRead = true
      this.setData({
        detail_data: t
      })
    } else {
      tool.showToast(re.content)
    }
  },

  async detail_handleDeleteNotification() {
    wx.showModal({
      title: '提示',
      content: '是否删除此通知，此操作不可恢复。',
      complete: async (res) => {
        if (res.cancel) {

        }

        if (res.confirm) {
          tool.loading.show()
          let re = await tool.requestMethod('/notification/delete', {
            account: this.data.loginedUserInfo.account,
            time: this.data.detail_data.time
          })
          tool.loading.hide()
          if (re.status == 1) {
            wx.showModal({
              title: '提示',
              content: '删除成功',
              showCancel:false,
              complete: (res) => {
                wx.navigateBack()
              }
            })
          } else {
            tool.showToast('删除失败')
          }
        }
      }
    })

  },

  userList_handleShowNtificationDetailPage(e) {
    tool.navigateTo(this, 'notification', {
      type: 'detail',
      time: e.currentTarget.dataset.time
    })
  },

  async init_userList() {
    tool.loading.show()
    this.setData({
      userList_page: 1,
    })
    let re = await tool.requestMethod('/notification/userList', {
      page: this.data.userList_page,
      size: this.data.userList_size,
      account: this.data.loginedUserInfo.account
    })
    tool.loading.hide()
    if (re.status == 1) {
      this.setData({
        userList_list: re.results.list,
        userList_unread: re.results.unread,
        userList_subScribe: re.results.subscribe
      })
    } else {
      wx.showModal({
        title: '提示',
        content: re.content,
        showCancel: false,
        complete: (res) => {
          wx.navigateBack()
        }
      })
    }
  },

  async userList_subScribe(e) {
    e = e.currentTarget.dataset.data
    wx.showModal({
      title: '提示',
      content: e ? '是否订阅通知？订阅后，通知通过短信发送到手机上，可以在第一时间收到通知。' : '是否取消订阅通知？',
      complete: async (res) => {
        if (res.cancel) {

        }

        if (res.confirm) {
          console.log(e)
          tool.loading.show()
          let re = await tool.requestMethod('/notification/subscribe', {
            account: this.data.loginedUserInfo.account
          })
          tool.loading.hide()
          if (re.status == 1) {
            tool.showToast('订阅成功')
            this.setData({
              userList_subScribe: e
            })
          } else {
            wx.showModal({
              title: '提示',
              content: re.content,
              showCancel: false,
              complete: (res) => {

              }
            })
          }
        }
      }
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    tool.setThemeColor(this)
    this.setData({
      sysImagURLPrefix: wx.getStorageSync('sysImagURLPrefix')
    })
    options = JSON.parse(options.data)
    this.setData({
      statusBarHeight: (parseInt(options.statusBarHeight.split('px')[0])).toString() + 'px',
      loginedUserInfo: options.loginedUserInfo,
      contentHeight: (parseInt(options.contentHeight.split('px')[0]) + 3).toString() + 'px',
      type: options.type
    })
    tool.loading.show()
    switch (options.type) {
      case 'management':
        this.setData({
          title: '通知管理'
        })
        await this.init_management()
        break;
      case 'add':
        this.setData({
          title: '新建通知'
        })
        await this.init_add()
        break;
      case 'detail':
        this.setData({
          title: '通知详情'
        })
        await this.init_detail(options)
        break;
      case 'userList':
        this.setData({
          title: '通知中心'
        })
        await this.init_userList()
        break;
    }
    this.setData({
      showPage: true
    })
    console.log(options)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

    if (this.data.userList_list != undefined) {
      this.init_userList()
    }

    if (this.data.management_list != undefined) {
      this.init_management()
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})